// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;

namespace SnapObjects.Data.AspNetCore
{
    internal class DynamicModelXmlOutputFormatter : XmlOutputFormatter
    {
        protected override bool CanWriteType(Type type)
        {
            if (typeof(DynamicModel).IsAssignableFrom(type) ||
                typeof(IEnumerable<DynamicModel>).IsAssignableFrom(type))
            {
                return base.CanWriteType(type);
            }

            return false;
        }

        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var response = context.HttpContext.Response;

            var json = String.Empty;

            if (context.Object is DynamicModel model)
            {
                json = model.ToXmlString();
            }
            else if (typeof(IEnumerable<DynamicModel>).IsAssignableFrom(context.Object.GetType()))
            {
                json = ((IEnumerable<DynamicModel>)context.Object).ToXmlString();
            }

            await response.WriteAsync(json);
        }
    }
}
